import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Separator } from "@/components/ui/separator"
import { ArrowLeft, Clock, Trophy, Users, Zap, Target, Shield, Coins } from 'lucide-react'
import { MatchDetail as MatchDetailType, Hero } from '../types/dota'
import { openDotaAPI } from '../services/api'
import { ItemImage } from './ItemImage'
import AdvantageChart from './AdvantageChart'
import PlayerEconomyCurveChart from './PlayerEconomyCurveChart'
import { getItemName, getItemDisplayName } from '../constants/items'

interface LeagueMatchDetailProps {
  matchId: string
  onBack: () => void
}

export default function LeagueMatchDetail({ matchId, onBack }: LeagueMatchDetailProps) {
  const [matchDetail, setMatchDetail] = useState<MatchDetailType | null>(null)
  const [heroes, setHeroes] = useState<{ [key: number]: Hero }>({})
  const [items, setItems] = useState<any>({})
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true)
        setError(null)

        // 并行获取比赛详情、英雄数据和道具数据
        const [matchData, heroData, itemData] = await Promise.all([
          openDotaAPI.getMatchDetail(matchId),
          openDotaAPI.getHeroes(),
          openDotaAPI.getItems()
        ])

        setMatchDetail(matchData)
        
        // 将英雄数据转换为以ID为键的对象
        const heroMap = heroData.reduce((acc: { [key: number]: Hero }, hero: Hero) => {
          acc[hero.id] = hero
          return acc
        }, {})
        setHeroes(heroMap)
        setItems(itemData)
        console.log('League Match Detail - Items data loaded:', itemData)
        console.log('League Match Detail - Items data keys:', Object.keys(itemData))

      } catch (error) {
        console.error('获取联赛比赛详情失败:', error)
        setError('获取联赛比赛详情失败')
      } finally {
        setLoading(false)
      }
    }

    if (matchId) {
      fetchData()
    }
  }, [matchId])

  const formatDuration = (seconds: number) => {
    const minutes = Math.floor(seconds / 60)
    const remainingSeconds = seconds % 60
    return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
  }

  const formatDate = (timestamp: number) => {
    return new Date(timestamp * 1000).toLocaleString('zh-CN')
  }

  const getGameMode = (mode: number) => {
    const modes: { [key: number]: string } = {
      0: '未知',
      1: '全选模式',
      2: '队长模式',
      3: '随机征召',
      4: '单选征召',
      5: '全随机',
      6: '介绍',
      7: '困难模式',
      8: '中路模式',
      9: '最少死亡模式',
      10: '联赛',
      11: '队长征召',
      12: '平衡征召',
      13: '能力征召',
      14: '全随机死亡竞赛',
      15: '1v1中路',
      16: '排位全选',
      17: '炮塔防御',
      18: '突变',
      19: '教程',
      20: '中路模式',
      21: '联赛',
      22: '排位',
      23: '1v1排位'
    }
    return modes[mode] || '未知模式'
  }

  const getHeroImageUrl = (heroName: string) => {
    const cleanName = heroName.replace('npc_dota_hero_', '')
    return `http://cdn.dota2.com/apps/dota2/images/heroes/${cleanName}_lg.png`
  }

  const getHeroName = (heroId: number) => {
    const hero = heroes[heroId]
    return hero ? hero.localized_name : `英雄 ${heroId}`
  }

  const formatGold = (gold: number) => {
    if (gold >= 1000) {
      return `${(gold / 1000).toFixed(1)}k`
    }
    return gold.toString()
  }

  const getKDA = (kills: number, deaths: number, assists: number) => {
    const kda = deaths === 0 ? kills + assists : (kills + assists) / deaths
    return kda.toFixed(2)
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"></div>
          <p>加载联赛比赛详情中...</p>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="text-center">
          <p className="text-red-500 mb-4">{error}</p>
          <Button onClick={onBack} variant="outline">
            <ArrowLeft className="mr-2 h-4 w-4" />
            返回联赛比赛列表
          </Button>
        </div>
      </div>
    )
  }

  if (!matchDetail) {
    return null
  }

  const radiantPlayers = matchDetail.players.filter(player => player.player_slot < 128)
  const direPlayers = matchDetail.players.filter(player => player.player_slot >= 128)

  return (
    <div className="space-y-6">
      {/* 头部信息 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-4">
          <Button onClick={onBack} variant="outline" size="sm">
            <ArrowLeft className="mr-2 h-4 w-4" />
            返回联赛比赛列表
          </Button>
          <div>
            <h1 className="text-2xl font-bold">
              <span>联赛比赛 #{matchDetail.match_id}</span>
            </h1>
            <p className="text-muted-foreground">
              {formatDate(matchDetail.start_time)} • {getGameMode(matchDetail.game_mode)}
            </p>
          </div>
        </div>
        <Badge 
          className="text-lg px-4 py-2" 
          variant={matchDetail.radiant_win ? "default" : "destructive"}
        >
          {matchDetail.radiant_win
            ? <Trophy className="mr-2 h-4 w-4" />
            : <Trophy className="mr-2 h-4 w-4" />
          }
          {matchDetail.radiant_win ? '天辉胜利' : '夜魇胜利'}
        </Badge>
      </div>

      {/* 比赛基本信息 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Clock className="mr-2 h-5 w-5" />
            联赛比赛信息
          </CardTitle>
        </CardHeader>
        <CardContent className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div className="flex items-center space-x-2">
            <Clock className="h-4 w-4 text-muted-foreground" />
            <span className="font-medium">时长:</span> {formatDuration(matchDetail.duration)}
          </div>
          <div className="flex items-center space-x-2">
            <Users className="h-4 w-4 text-muted-foreground" />
            <span className="font-medium">玩家:</span> {matchDetail.human_players}
          </div>
          <div className="flex items-center space-x-2">
            <Target className="h-4 w-4 text-muted-foreground" />
            <span className="font-medium">比分:</span> {matchDetail.radiant_score} - {matchDetail.dire_score}
          </div>
          <div className="flex items-center space-x-2">
            <Zap className="h-4 w-4 text-muted-foreground" />
            <span className="font-medium">首杀:</span> {Math.floor(matchDetail.first_blood_time / 60)}:{(matchDetail.first_blood_time % 60).toString().padStart(2, '0')}
          </div>
          {matchDetail.leagueid && matchDetail.leagueid > 0 && (
            <div className="flex items-center space-x-2 col-span-2">
              <Trophy className="h-4 w-4 text-muted-foreground" />
              <span className="font-medium">联赛:</span> {matchDetail.leagueid}
            </div>
          )}
        </CardContent>
      </Card>

      {/* 经济/经验曲线 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Zap className="mr-2 h-5 w-5" />
            经济/经验曲线
          </CardTitle>
          <CardDescription>每分钟优势走势（天辉为正，夜魇为负）</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <AdvantageChart title="经济优势（每分钟）" data={matchDetail.radiant_gold_adv || []} />
            <AdvantageChart title="经验优势（每分钟）" data={matchDetail.radiant_xp_adv || []} />
          </div>
        </CardContent>
      </Card>

      {/* 玩家经济曲线 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Coins className="mr-2 h-5 w-5" />
            玩家经济曲线
          </CardTitle>
          <CardDescription>20位玩家的经济发展曲线对比</CardDescription>
        </CardHeader>
        <CardContent>
          <PlayerEconomyCurveChart 
            players={matchDetail.players} 
            duration={matchDetail.duration}
            title="玩家净值变化曲线"
          />
        </CardContent>
      </Card>

      {/* 天辉队伍 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center justify-between">
            <div className="flex items-center">
              <div className="w-4 h-4 bg-green-500 rounded mr-2"></div>
              天辉 (Radiant)
              {matchDetail.radiant_win && <Trophy className="h-4 w-4 text-yellow-500" />}
            </div>
            <Badge variant="outline">{matchDetail.radiant_score} 击杀</Badge>
          </CardTitle>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>英雄</TableHead>
                <TableHead>玩家</TableHead>
                <TableHead>等级</TableHead>
                <TableHead>K/D/A</TableHead>
                <TableHead>KDA</TableHead>
                <TableHead>金钱</TableHead>
                <TableHead>补刀</TableHead>
                <TableHead>反补</TableHead>
                <TableHead>装备</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {radiantPlayers.map((player, index) => (
                <TableRow key={index}>
                  <TableCell>
                    <div className="flex items-center space-x-2">
                      {heroes[player.hero_id] && (
                        <img
                          src={getHeroImageUrl(heroes[player.hero_id].name)}
                          alt={heroes[player.hero_id].localized_name}
                          className="w-12 h-8 rounded border border-border object-cover"
                          onError={(e) => {
                            const target = e.target as HTMLImageElement
                            if (!target.src.includes('_sb.png')) {
                              const cleanName = heroes[player.hero_id].name.replace('npc_dota_hero_', '')
                              target.src = `http://cdn.dota2.com/apps/dota2/images/heroes/${cleanName}_sb.png`
                            }
                          }}
                        />
                      )}
                      <span className="font-medium">{getHeroName(player.hero_id)}</span>
                    </div>
                  </TableCell>
                  <TableCell>
                    {player.personaname || player.account_id || '匿名玩家'}
                  </TableCell>
                  <TableCell>{player.level}</TableCell>
                  <TableCell>
                    <span className="text-green-600">{player.kills}</span>/
                    <span className="text-red-600">{player.deaths}</span>/
                    <span className="text-blue-600">{player.assists}</span>
                  </TableCell>
                  <TableCell>
                    <Badge variant="outline">
                      {getKDA(player.kills, player.deaths, player.assists)}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center space-x-1">
                      <Coins className="h-3 w-3 text-yellow-500" />
                      <span>{formatGold(player.total_gold)}</span>
                    </div>
                  </TableCell>
                  <TableCell>{player.last_hits}</TableCell>
                  <TableCell>{player.denies}</TableCell>
                  <TableCell>
                    <div className="flex space-x-1">
                      {[
                        player.item_0, player.item_1, player.item_2,
                        player.item_3, player.item_4, player.item_5
                      ].map((itemId, itemIndex) => (
                        <div key={itemIndex} className="w-6 h-6">
                          {itemId > 0 && (
                            <ItemImage 
                              itemId={itemId} 
                              className="w-6 h-4"
                            />
                          )}
                        </div>
                      ))}
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* 夜魇队伍 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center justify-between">
            <div className="flex items-center">
              <div className="w-4 h-4 bg-red-500 rounded mr-2"></div>
              夜魇 (Dire)
              {!matchDetail.radiant_win && <Trophy className="h-4 w-4 text-yellow-500" />}
            </div>
            <Badge variant="outline">{matchDetail.dire_score} 击杀</Badge>
          </CardTitle>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>英雄</TableHead>
                <TableHead>玩家</TableHead>
                <TableHead>等级</TableHead>
                <TableHead>K/D/A</TableHead>
                <TableHead>KDA</TableHead>
                <TableHead>金钱</TableHead>
                <TableHead>补刀</TableHead>
                <TableHead>反补</TableHead>
                <TableHead>装备</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {direPlayers.map((player, index) => (
                <TableRow key={index}>
                  <TableCell>
                    <div className="flex items-center space-x-2">
                      {heroes[player.hero_id] && (
                        <img
                          src={getHeroImageUrl(heroes[player.hero_id].name)}
                          alt={heroes[player.hero_id].localized_name}
                          className="w-12 h-8 rounded border border-border object-cover"
                          onError={(e) => {
                            const target = e.target as HTMLImageElement
                            if (!target.src.includes('_sb.png')) {
                              const cleanName = heroes[player.hero_id].name.replace('npc_dota_hero_', '')
                              target.src = `http://cdn.dota2.com/apps/dota2/images/heroes/${cleanName}_sb.png`
                            }
                          }}
                        />
                      )}
                      <span className="font-medium">{getHeroName(player.hero_id)}</span>
                    </div>
                  </TableCell>
                  <TableCell>
                    {player.personaname || player.account_id || '匿名玩家'}
                  </TableCell>
                  <TableCell>{player.level}</TableCell>
                  <TableCell>
                    <span className="text-green-600">{player.kills}</span>/
                    <span className="text-red-600">{player.deaths}</span>/
                    <span className="text-blue-600">{player.assists}</span>
                  </TableCell>
                  <TableCell>
                    <Badge variant="outline">
                      {getKDA(player.kills, player.deaths, player.assists)}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center space-x-1">
                      <Coins className="h-3 w-3 text-yellow-500" />
                      <span>{formatGold(player.total_gold)}</span>
                    </div>
                  </TableCell>
                  <TableCell>{player.last_hits}</TableCell>
                  <TableCell>{player.denies}</TableCell>
                  <TableCell>
                    <div className="flex space-x-1">
                      {[
                        player.item_0, player.item_1, player.item_2,
                        player.item_3, player.item_4, player.item_5
                      ].map((itemId, itemIndex) => (
                        <div key={itemIndex} className="w-6 h-6">
                          {itemId > 0 && (
                            <ItemImage 
                              itemId={itemId} 
                              className="w-6 h-4"
                            />
                          )}
                        </div>
                      ))}
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  )
}